<?php
namespace GRH\Controller;

use GRH\Model\Periode;
use GRH\Model\Table\PeriodeTable;
use GRH\Form\PeriodeForm;

use GRH\Model\Semaine;
use GRH\Model\Table\SemaineTable;
use GRH\Model\PeriodeDetails;
use GRH\Model\Table\PeriodeDetailsTable;
use GRH\Model\Planning;

class PeriodeController extends BaseController
{
    /**
     * Liste toutes les périodes
     * Création d'une nouvelle période
     * Edition d'une période
     * 
     * @return array
     */
    public function indexAction()
    {
        /**
         * @var PeriodeTable $periodeTable
         */
        $periodeTable = $this->getService('GRH\Model\Table\PeriodeTable');
        $newPeriode = new PeriodeForm();
        $nextMondays = $periodeTable->getNextMonday();
        //var_dump($nextMondays);
        $newPeriode->get('debut_periode')->setValueOptions($nextMondays);
        $monday = '';
        foreach($nextMondays as $key => $value)
        {
            $newPeriode->get('debut_periode')->setValue($key);
            $monday = $key;
            break;
        }
        $nextSundays = $periodeTable->getNextSunday($monday);
        $newPeriode->get('fin_periode')->setValueOptions($nextSundays);
        foreach($nextSundays as $key => $value)
        {
            $newPeriode->get('fin_periode')->setValue($key);
        }
        $nextLabel = $periodeTable->getNextLabel();
        $newPeriode->get('libelle')->setValue($nextLabel);
        return array(
            'periode_list' => $periodeTable->getAll(),
            'max_id' => $periodeTable->getMaxValue(),
            'newPeriode' => $newPeriode,
        );
    }
    
    /**
     * Ajouter une Période
     * Ajouter les semaines de cette période
     * Ajouter les détails de cette période
     * Générer les plannings correspondant
     * 
     * @return type
     */
    public function addAction()
    {
        $periodeTable = $this->getService('GRH\Model\Table\PeriodeTable');
        $request = $this->getRequest();
        $data = $request->getPost();
        // Sauvegarde de la période
        $periode = new Periode();
        $periode->exchangeArray($data);
        $periode_id = $periodeTable->save($periode);
        $periode->periode_id = $periode_id;
        // Sauvegarde des semaines
        $debut = $data->get('debut_periode');
        $fin = $data->get('fin_periode');
        $dateDebut = new \DateTime($debut);
        $dateFin = new \DateTime($fin);
        $dateFin->modify('next day');
        $jours = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche');
        $interval = new \DateInterval('P1W'); // 1 semaine
        $weeks = new \DatePeriod($dateDebut, $interval, $dateFin);
        /**
         * @var SemaineTable $semaineTable
         */
        $semaineTable = $this->getService('GRH\Model\Table\SemaineTable');
        /**
         * @var PeriodeDetailsTable $periodeDetailsTable
         */
        $periodeDetailsTable = $this->getService('GRH\Model\Table\PeriodeDetailsTable');
        $semaines = array();
        $i = 1;
        foreach($weeks as $week)
        {
            $end = clone $week;
            $end->modify('next monday');
            $dayInterval = new \DateInterval('P1D'); // 1 jour
            $daysOfWeek = new \DatePeriod($week, $dayInterval, $end);
            $j = 0;
            $data = array();
            $data['libelle'] = 'Semaine ' .$i++;
            var_dump($daysOfWeek);
            foreach($daysOfWeek as $day)
            {
                var_dump($day);
                $data[$jours[$j++]] = $day->format('Y-m-d');
            }
            $semaine = new Semaine();
            $semaine->exchangeArray($data);
            $id = $semaineTable->save($semaine);
            $semaine->semaine_id = $id;
            $semaines[] = $semaine;
            
            // Sauvegarde dans les détails de période
            $details = new PeriodeDetails();
            $details->periode_id = $periode->periode_id;
            $details->semaine_id = $semaine->semaine_id;
            $periodeDetailsTable->save($details);
        }
        
        // Génération des plannings
        $planningTable = $this->getService('GRH\Model\Table\PlanningTable');
        $disponibiliteTable = $this->getService('GRH\Model\Table\DisponibiliteTable');
        $employeTable = $this->getService('GRH\Model\Table\EmployeTable');
        $siteId = 1;
        $employeListBySite = $employeTable->getAllBySite($siteId);
        $employeData = array();
        foreach($employeListBySite as $employe)
        {
            $e = array(
                'data' => $employe,
                'dispo' => $disponibiliteTable->getByEmploye($employe->employe_id),
            );
            $employeData[$employe->employe_id] = $e;
        }
        $plannings = array();
        foreach($semaines as $sem)
        {
            for($jr = 1; $jr < 8; $jr++)
            {
                $e = 1;
                foreach($employeData as $emp)
                {
                    $data = $emp['data'];
                    $dispo = $emp['dispo'];
                    $journee = '';
                    $code = 3;
                    $entree = '00:00';
                    $sortie = '00:00';
                    switch($jr)
                    {
                        case 1:
                            // Lundi
                            $journee = $sem->lundi;
                            $allow = (int)$dispo->lundi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->lundi_entree;
                                $sortie = $dispo->lundi_sortie;
                            }
                            break;
                        case 2:
                            // Mardi
                            $journee = $sem->mardi;
                            $allow = (int)$dispo->mardi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->mardi_entree;
                                $sortie = $dispo->mardi_sortie;
                            }
                            break;
                        case 3:
                            // Mercredi
                            $journee = $sem->mercredi;
                            $allow = (int)$dispo->mercredi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->mercredi_entree;
                                $sortie = $dispo->mercredi_sortie;
                            }
                            break;
                        case 4:
                            // jeudi
                            $journee = $sem->jeudi;
                            $allow = (int)$dispo->jeudi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->jeudi_entree;
                                $sortie = $dispo->jeudi_sortie;
                            }
                            break;
                        case 5:
                            // vendredi
                            $journee = $sem->vendredi;
                            $allow = (int)$dispo->vendredi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->vendredi_entree;
                                $sortie = $dispo->vendredi_sortie;
                            }
                            break;
                        case 6:
                            // samedi
                            $journee = $sem->samedi;
                            $allow = (int)$dispo->samedi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->samedi_entree;
                                $sortie = $dispo->samedi_sortie;
                            }
                            break;
                        case 7:
                            // dimanche
                            $journee = $sem->dimanche;
                            $allow = (int)$dispo->dimanche;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->dimanche_entree;
                                $sortie = $dispo->dimanche_sortie;
                            }
                            break;
                    }
                    // Sauvegarde du planning
                    $plan = new Planning();
                    $plan->employe_id = $data->employe_id;
                    $plan->code_activite_id = $code;
                    $plan->journee = $journee;
                    $plan->heure_entree = $entree;
                    $plan->heure_sortie = $sortie;
                    $plan->pause = 0;
                    $plan->repas = 0;
                    $planningTable->add($plan);
                }
            }
        }
        
        return $this->redirect()->toRoute('GRH/default', array('controller' => 'periode'));
    }
    
    /**
     * Introduction à la génération des Périodes
     * On fournit les données nécessaire
     * 
     * @return type
     */
    public function generateAction()
    {
        $this->layout('layout/ajax');
        $request = $this->getRequest();
        $data = $request->getPost();
        
        return array(
            'libelle' => $data['libelle'],
            'debut' => $data['debut_periode'],
            'fin' => $data['fin_periode'],
        );
    }
    
    /**
     * Génération de la période
     * 
     * @return type
     */
    public function generateperiodAction()
    {
        $this->layout('layout/ajax');
        $periodeTable = $this->getService('GRH\Model\Table\PeriodeTable');
        $request = $this->getRequest();
        $data = $request->getPost();
        // Sauvegarde de la période
        $periode = new Periode();
        $periode->exchangeArray($data);
        $periode_id = $periodeTable->save($periode);
        $periode->periode_id = $periode_id;
        
        return array(
            'periode' => $periode,
            'debut' => $periode->debut_periode,
            'fin' => $periode->fin_periode,
            'id' => $periode->periode_id,
        );
    }
    
    /**
     * Génération des semaines
     * 
     * @return type
     */
    public function generateweekAction()
    {
        $this->layout('layout/ajax');
        $request = $this->getRequest();
        $data = $request->getPost();
        //var_dump($data);
        $debut = $data['debut'];
        $fin = $data['fin'];
        $periode_id = $data['periode_id'];
        $dateDebut = new \DateTime($debut);
        $dateFin = new \DateTime($fin);
        $dateFin->modify('next day');
        $jours = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche');
        $interval = new \DateInterval('P1W'); // 1 semaine
        $weeks = new \DatePeriod($dateDebut, $interval, $dateFin);
        /**
         * @var SemaineTable $semaineTable
         */
        $semaineTable = $this->getService('GRH\Model\Table\SemaineTable');
        /**
         * @var PeriodeDetailsTable $periodeDetailsTable
         */
        $periodeDetailsTable = $this->getService('GRH\Model\Table\PeriodeDetailsTable');
        $semaines = array();
        $i = 1;
        //echo "Début : $debut<br>";var_dump($dateDebut);
        //echo "Fin : $fin<br>";var_dump($dateFin);
        foreach($weeks as $week)
        {
            $end = clone $week;
            $end->modify('next monday');
            $dayInterval = new \DateInterval('P1D'); // 1 jour
            $daysOfWeek = new \DatePeriod($week, $dayInterval, $end);
            $j = 0;
            $data = array();
            $data['libelle'] = 'Semaine ' .$i++;
            foreach($daysOfWeek as $day)
            {
                //var_dump($day);
                $data[$jours[$j++]] = $day->format('Y-m-d');
            }
            $semaine = new Semaine();
            $semaine->exchangeArray($data);
            $id = $semaineTable->save($semaine);
            $semaine->semaine_id = $id;
            $semaines[] = $semaine;
            
            // Sauvegarde dans les détails de période
            $details = new PeriodeDetails();
            $details->periode_id = (int)$periode_id;
            $details->semaine_id = $semaine->semaine_id;
            $periodeDetailsTable->save($details);
        }
        
        return array(
            'semaines' => $semaines,
        );
    }
    
    /**
     * Génération des détails
     * 
     * @return type
     */
    public function generatedetailsAction()
    {
        $this->layout('layout/ajax');
        $request = $this->getRequest();
        $data = $request->getPost();
        $semaines = $data['semaines'];
        
        return array(
            'semaines' => $semaines,
        );
    }
    
    /**
     * Génération des plannings de tous les employés du site
     */
    public function generateplanningAction()
    {
        $this->layout('layout/ajax');
        $request = $this->getRequest();
        $data = $request->getPost();
        $semaines_id = $data['semaines'];
        $semaineTable = $this->getService('GRH\Model\Table\SemaineTable');
        $semaines = $semaineTable->getByArray($semaines_id);
        $planningTable = $this->getService('GRH\Model\Table\PlanningTable');
        $disponibiliteTable = $this->getService('GRH\Model\Table\DisponibiliteTable');
        $employeTable = $this->getService('GRH\Model\Table\EmployeTable');
        $siteId = 1;
        $employeListBySite = $employeTable->getAllBySite($siteId);
        $employeData = array();
        foreach($employeListBySite as $employe)
        {
            $e = array(
                'data' => $employe,
                'dispo' => $disponibiliteTable->getByEmploye($employe->employe_id),
            );
            $employeData[$employe->employe_id] = $e;
        }
        $plannings = array();
        foreach($semaines as $sem)
        {
            for($jr = 1; $jr < 8; $jr++)
            {
                $e = 1;
                foreach($employeData as $emp)
                {
                    $data = $emp['data'];
                    $dispo = $emp['dispo'];
                    $journee = '';
                    $code = 3;
                    $entree = '00:00';
                    $sortie = '00:00';
                    switch($jr)
                    {
                        case 1:
                            // Lundi
                            $journee = $sem->lundi;
                            $allow = (int)$dispo->lundi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->lundi_entree;
                                $sortie = $dispo->lundi_sortie;
                            }
                            break;
                        case 2:
                            // Mardi
                            $journee = $sem->mardi;
                            $allow = (int)$dispo->mardi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->mardi_entree;
                                $sortie = $dispo->mardi_sortie;
                            }
                            break;
                        case 3:
                            // Mercredi
                            $journee = $sem->mercredi;
                            $allow = (int)$dispo->mercredi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->mercredi_entree;
                                $sortie = $dispo->mercredi_sortie;
                            }
                            break;
                        case 4:
                            // jeudi
                            $journee = $sem->jeudi;
                            $allow = (int)$dispo->jeudi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->jeudi_entree;
                                $sortie = $dispo->jeudi_sortie;
                            }
                            break;
                        case 5:
                            // vendredi
                            $journee = $sem->vendredi;
                            $allow = (int)$dispo->vendredi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->vendredi_entree;
                                $sortie = $dispo->vendredi_sortie;
                            }
                            break;
                        case 6:
                            // samedi
                            $journee = $sem->samedi;
                            $allow = (int)$dispo->samedi;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->samedi_entree;
                                $sortie = $dispo->samedi_sortie;
                            }
                            break;
                        case 7:
                            // dimanche
                            $journee = $sem->dimanche;
                            $allow = (int)$dispo->dimanche;
                            if($allow != 0)
                            {
                                $code = 1;
                                $entree = $dispo->dimanche_entree;
                                $sortie = $dispo->dimanche_sortie;
                            }
                            break;
                    }
                    // Sauvegarde du planning
                    $plan = new Planning();
                    $plan->employe_id = $data->employe_id;
                    $plan->code_activite_id = $code;
                    $plan->journee = $journee;
                    $plan->heure_entree = $entree;
                    $plan->heure_sortie = $sortie;
                    $plan->pause = 0;
                    $plan->repas = 0;
                    $planningTable->add($plan);
                }
            }
        }
    }
}